"""
/** Copyright 2020 Zhejiang Lab and Zhejiang University. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================
*/
"""
from server.models import Server
from utils import logRequest
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAdminUser, AllowAny
from django.utils import timezone
import logging
# Create your views here.
logger_name = 'server.views'
logger = logging.getLogger(logger_name)

class Servers(APIView):
    permission_classes = (IsAdminUser,)
    @logRequest(logger_name)
    def get(self, request, format=None):
        servers = Server.objects.all()
        logger.debug(request.data)
        servers = [{'id': s.id, 'username': s.username, 'last_login': s.last_login} for s in servers]
        return Response({'servers': servers}, status=status.HTTP_200_OK)

    @logRequest(logger_name)
    def post(self, request, format=None):
        # Create 
        server_info = request.data.get('server_info', None)
        if server_info is None:
            return Response({'error': 'Parameter errors'}, status=status.HTTP_400_BAD_REQUEST)
        username = server_info.get('username', None)
        password = server_info.get('password', None)
        if None in (username, password):
            return Response({'error': 'Parameter errors'}, status=status.HTTP_400_BAD_REQUEST)
        logger.debug(username, password)
        try:
            server = Server.objects.create(username=username, password=password)
        except Exception as e:
            logger.debug(e)
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

        return Response({'response': 'success'}, status=status.HTTP_201_CREATED)

    # def put(self, request, format=None):
    #     # Modify
    #     server_info = request.data.get('server_info', None)
    #     if server_info is None:
    #         return Response({'error': 'Parameter errors'}, status=status.HTTP_400_BAD_REQUEST)
    #     username = server_info.get('username', None)
    #     old_password = server_info.get('old_password', None)
    #     new_password = server_info.get('new_password', None)
    #     if None in (username, password):
    #         return Response({'error': 'Parameter errors'}, status=status.HTTP_400_BAD_REQUEST)
    #     print(username, password)
    #     try:
    #         server = Server.objects.get(username=username)
    #     except Server.DoesNotExist as e:
    #         return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

    #     if not server.check_password(old_password):
    #         return Response({'error': 'Wrong old password'}, status=status.HTTP_400_BAD_REQUEST)
    #     server.set_password(new_password)
    #     server.last_login = timezone.now()
    #     server.save()
    #     return Response({'response': 'success'}, status=status.HTTP_200_OK)

    @logRequest(logger_name)
    def delete(self, request, format=None):
        server_ids = [int(v) for v in request.query_params.getlist('server_ids[]', [])]
        logger.debug(server_ids)
        try:
            server = Server.objects.filter(id__in=server_ids).delete()
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

        return Response({'response': 'success'}, status=status.HTTP_200_OK)